package core.manager
{
import core.resources.MapResourceManager;
import core.resources.ResourceManagerBase;

import flash.events.Event;
import flash.events.ProgressEvent;
import flash.utils.Dictionary;

import mapengine.IsoMap;
import mapengine.interfaces.IIsoMap;

/**
 * MapManager
 * @author jliang
 *
 */
public class MapManager
{
	private static var CACHE:Dictionary = new Dictionary(true);   /* MapCache */
	
	private static var currentCache:MapCache;
	
	public static function loadMap(url:String, onComplete:Function, onCompleteParams:Array = null):void
	{
		currentCache = CACHE[url];
		if (!currentCache)
		{
			currentCache = new MapCache();
			currentCache.url = url;
			currentCache.onComplete = onComplete;
			currentCache.onCompleteParams = onCompleteParams;
			
			CACHE[url] = currentCache;
		}
		
		var resource:ResourceManagerBase = new MapResourceManager();
		resource.params = { url:currentCache.url, data:currentCache.data, lib:currentCache.lib };
		resource.addEventListener(Event.COMPLETE, loadedHandler);
		resource.addEventListener(ProgressEvent.PROGRESS, progressHandler);
		resource.start();
	}
	
	private static var map:IIsoMap;
	
	public static function removeMap():void
	{
		map.dispose();
		map.parentContainer.removeChild(map as IsoMap);
	}
	
	private static function loadedHandler(event:Event):void
	{
		var resource:ResourceManagerBase = ResourceManagerBase(event.target);
		resource.removeEventListener(Event.COMPLETE, loadedHandler);
		resource.removeEventListener(ProgressEvent.PROGRESS, progressHandler);
		
		currentCache.data = resource.params.data;
		currentCache.lib = resource.params.lib;
		
		/*
		生成地图
		var isoMap:IsoMap = new IsoMap();
		isoMap.initialize(_appDomain, _mapValue);
		
		所有地图操作
		isoMap.addSprite(...);
		isoMap.removeSprite(...);
		*/		
		
		map = new IsoMap();
		map.initialize(currentCache.lib, currentCache.data);
		
		MapBuildingManager.setWorld(map);
		
		if (currentCache.onComplete != null)
		{
			var params:Array = [ map ];
			if (currentCache.onCompleteParams)
			{
				params = params.concat(currentCache.onCompleteParams);
			}
			currentCache.onComplete.apply(currentCache, params);
		}
		currentCache.onComplete = null;
		currentCache.onCompleteParams = null;
	}
	
	private static function progressHandler(event:Event):void
	{
		
	}
}
}
import flash.system.ApplicationDomain;

import values.map.MapValue;

class MapCache
{
	public var url:String;
	
	public var data:MapValue;
	
	public var lib:ApplicationDomain;
	
	public var onComplete:Function;
	
	public var onCompleteParams:Array;
}



